package com.yxsk.relay.job.admin.web.common.aop;

import com.yxsk.relay.job.admin.web.common.exception.RelayAdminWebRestfulRuntimeException;
import com.yxsk.relay.job.admin.web.common.exception.RelayAdminWebRuntimeException;
import com.yxsk.relay.job.component.common.exception.RelayJobException;
import com.yxsk.relay.job.component.common.exception.RelayJobRuntimeException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;

/**
 * @Author 11376
 * @CreaTime 2019/8/1 10:11
 * @Description
 */
@Aspect
@Component
public class ControllerExceptionWrapper {

    @Pointcut("execution(* com.yxsk.relay.job.admin.web..*Controller.*(..))")
    public void exceptionPoint() {
    }

    @Around("exceptionPoint()")
    public Object wrapper(ProceedingJoinPoint point) throws Throwable {

        try {
            return point.proceed(point.getArgs());
        } catch (Exception e) {
            // 包装异常
            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();

            // 方法响应类型
            boolean isRestful = method.getAnnotation(ResponseBody.class) != null || point.getTarget().getClass().getAnnotation(RestController.class) != null;

            if (isRestful) {
                if (e instanceof RelayJobException) {
                    throw new RelayAdminWebRestfulRuntimeException((RelayJobException) e);
                }
                if (e instanceof RelayJobRuntimeException) {
                    throw new RelayAdminWebRestfulRuntimeException((RelayJobRuntimeException) e);
                }
                if (e instanceof RelayAdminWebRuntimeException) {
                    throw new RelayAdminWebRestfulRuntimeException((RelayAdminWebRuntimeException) e);
                }
                throw new RelayAdminWebRestfulRuntimeException(e);
            }

            if (e instanceof RelayAdminWebRuntimeException) {
                throw e;
            }
            if (e instanceof RelayJobException) {
                throw new RelayAdminWebRuntimeException((RelayJobException) e);
            }
            if (e instanceof RelayJobRuntimeException) {
                throw new RelayAdminWebRuntimeException((RelayJobRuntimeException) e);
            }
            throw new RelayAdminWebRuntimeException(e);
        }

    }

}
